<?php

namespace App\Http\Middleware;

use Closure;
use Log;
use App\Services\JwtService;
use App\Services\RoleAccessService;
use Illuminate\Http\Request;
use App\Exceptions\InvalidException;
class TokenApiMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // dump($request->getRequestUri());
         // dump($request->getMethod());
        $token = $request->header('authorization');
        if(!$token) {
             throw new InvalidException("请登录");
        }
        $token = substr($token, 7);
        $jwtService = new JwtService();
        try{
            $jwt = $jwtService->parseToken($token);
            $data = $jwt->data->id;
            define('USER_ID', $id);
            // var_dump($jwt);
        }catch(\Exception $e) {
            throw new InvalidException("请登录".$e->getMessage());
        }
        Log::info($request->path());
        // //验证权限
        // $roleAccessService = new RoleAccessService();
        // if(!$roleAccessService->permit($jwt->id,$request->path(),$request->getMethod())) {
        //     throw new InvalidException("没有权限，请联系管理员添加");
        // }
        return $next($request);
    }
}
